package com.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.util.StringToken;

public class LoginFilter implements Filter {

	private String indexPage = null;

	public void destroy() {

	}

	// jsp页面请求过滤器，防止未登陆用户对页面的非法访问
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		Object obj = request.getSession()
				.getAttribute(StringToken.CURRENT_LOGIN);
		if (obj == null) {
			String url = request.getContextPath() + indexPage;
			java.io.PrintWriter out = response.getWriter();
		    out.println("<html>");
		    out.println("<script>");
		    out.println("window.open ('" + url + "', '_top')");
		    out.println("</script>");
		    out.println("</html>");
		    out.flush();
			return;
		}
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig config) throws ServletException {
		indexPage = config.getInitParameter("indexPage");
	}

}
